package com.hit.demo1.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import com.hit.demo1.entity.FileInfo;
import com.hit.demo1.service.FileInfoService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;

@RestController
@CrossOrigin(origins = "*")
public class HelloController2 {

    @Autowired
    FileInfoService fileInfoService;

    @PostMapping(value = "/upload2")
    public String upload(MultipartFile file) throws IOException {
        if(null != file){
            String path = "D:\\";
            String fileSub = file.getOriginalFilename().split("\\.")[1];
            String fileName = UUID.fastUUID().toString()+"."+fileSub;
            FileUtil.writeFromStream(file.getInputStream(),path+fileName);
            FileInfo fileInfo = new FileInfo();
            fileInfo.setFileName(file.getOriginalFilename());
            fileInfo.setFilePath(path+fileName);
            fileInfoService.add(fileInfo);
            return "ok";
        }
        return "no";
    }

    @RequestMapping(value = "/download")
    public void download(int id , HttpServletResponse response) throws IOException {
        OutputStream os;//新建一个输出流对象
        FileInfo fileInfo = fileInfoService.findById(id);

        try {
            if (ObjectUtil.isNotNull(fileInfo)) {
               File file = new File(fileInfo.getFilePath());
                long length = file.length();
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileInfo.getFileName(), "UTF-8"));
                response.setContentType("application/octet-stream");
                response.setContentLengthLong(length);
                byte[] bytes = FileUtil.readBytes(file);//通过文件的路径读取文件字节流
                os = response.getOutputStream();//通过response的输出流返回文件
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
